<template>
  <div>
    <a-card>
      <a-form-model ref="form" layout="inline" :model="form">
        <a-row type="flex" v-if="['me', 'join'].indexOf(type)>-1">
          <a-col flex="180px">
            <a-form-model-item label="状态" prop="state">
              <a-select
                v-model="form.state"
                placeholder="请选择状态"
                style="width:120px"
                :options="[
                  { value: 'NEW', label: '创建中' },
                  { value: 'RECRUIT', label: '招募中' },
                  { value: 'IN_PROGRESS', label: '执行中' },
                  { value: 'DONE', label: '已完成' },
                  { value: 'ABANDONED', label: '已废弃' },
                ]"
              />
            </a-form-model-item>
          </a-col>
          <a-col flex="410px">
            <a-form-model-item label="到期日" prop="dueDate">
              <a-range-picker
                v-model="form.dueDate"
              />
            </a-form-model-item>
          </a-col>
          <a-col flex="80px">
            <a-form-model-item>
              <a-button type="primary" @click="handleSearch">
                查找
              </a-button>
            </a-form-model-item>
          </a-col>
          <a-col flex="80px">
            <a-form-model-item>
              <a-button type="primary" @click="handleReset">
                重置
              </a-button>
            </a-form-model-item>
          </a-col>
          <a-col flex="auto">
            <a-form-model-item style="float:right;">
              <a-button type="primary" @click="showEditInstanceModal(undefined)">
                新增
              </a-button>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>

      <a-table
        :loading="loading"
        rowKey="id"
        :columns="columns"
        :data-source="data"
        class="instance-list__table"
        :expandedRowKeys="expandedRowKeys"
        @expand="expand"
      >
        <template slot="status" slot-scope="record">
          <span v-if="record.state === 'NEW'"><a-badge color="lime" /> {{ record.stateDesc }}</span>
          <span v-if="record.state === 'RECRUIT'"><a-badge color="#2db7f5" /> {{ record.stateDesc }}</span>
          <span v-if="record.state === 'IN_PROGRESS'"><a-badge color="gold" /> {{ record.stateDesc }}</span>
          <span v-if="record.state === 'DONE'"><a-badge color="green" /> {{ record.stateDesc }}</span>
          <span v-if="record.state === 'ABANDONED'"><a-badge color="volcano" /> {{ record.stateDesc }}</span>
        </template>
        <template slot="operation" slot-scope="record" >
          <div>
            <router-link :to="`/instance/detail/${record.id}`" style="margin-right: 10px">详情</router-link>
            <!-- 自己才能删除编辑自己的 -->
            <a v-if="type==='me'" @click="del(record.id)" style="margin-right: 10px">删除</a>
            <a v-if="type==='me'" @click="showEditInstanceModal(record)" style="margin-right: 10px">编辑</a>
            <a v-if="['me'].indexOf(type) > -1" @click="showAddMissionModal(record)">添加目标</a>
          </div>
        </template>

        <a-table
          rowKey="id"
          slot="expandedRowRender"
          slot-scope="record"
          :loading="record.loading"
          :columns="innerColumns"
          :data-source="record.missionList"
        >
          <template slot="status" slot-scope="missionRecorc">
            <span v-if="missionRecorc.state === 'NEW'"><a-badge status="processing" /> {{ missionRecorc.stateDesc }}</span>
            <span v-if="missionRecorc.state === 'DONE'"><a-badge status="success" /> {{ missionRecorc.stateDesc }}</span>
          </template>
          <span slot="operation" slot-scope="missionRecorc" class="table-operation">
            <a v-if="type==='me'" @click="removeMission(record, missionRecorc.id)">删除</a>
          </span>
        </a-table>
      </a-table>
    </a-card>
    <!-- 编辑模块 -->
    <edit-instance-modal ref="editInstanceModal" @update-list="updateList" />
    <!-- 新增加任务 -->
    <add-mission-modal ref="addMissionModal" @mission-added="updateMissionList" />
  </div>
</template>

<script>
// 组件
import EditInstanceModal from './modal/edit-instance'
import AddMissionModal from './modal/add-mission'

// api
import { fetchMyInstances, fetchAllInstances, fetchMyJoinInstances, detail, removeMission, del } from '@/api/instance'

// constants
import { columns, innerColumns } from './constants'

export default {
  name: 'InstanceList',
  components: {
    EditInstanceModal,
    AddMissionModal
  },
  props: {
    type: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      loading: false,
      form: {
        state: undefined,
        dueDate: undefined
      },
      expandedRowKeys: [],
      pagination: {
        pageSize: 10,
        current: 1,
        total: 0
      },
      columns,
      data: [],
      innerColumns
    }
  },
  mounted () {
    this.handleSearch(true)
  },
  methods: {
    // 清空团战表单
    handleReset () {
      this.$refs.form.resetFields()
    },
    // 查询
    async handleSearch (valid) {
      try {
        this.loading = true
        if (!valid) { throw new Error() }

        let fetchInstances = () => {}

        const data = {
          ...this.form,
          pageNumber: 1,
          pageSize: 1000
        }

        switch (this.type) {
          case 'all':
            fetchInstances = fetchAllInstances
            data.state = 'RECRUIT'
            break
          case 'me':
            fetchInstances = fetchMyInstances
            break
          case 'join':
            fetchInstances = fetchMyJoinInstances
            break
        }

        if (this.form.dueDate && this.form.dueDate.length === 2) {
          data.startDate = this.form.dueDate[0].format('YYYYMMDD')
          data.endDate = this.form.dueDate[0].format('YYYYMMDD')
        }

        delete data.dueDate

        const content = await fetchInstances(data)
        content.forEach(record => {
          record.loading = false
          record.missionList = []
        })
        this.data = content
        return false
      } catch (error) {
        console.error(error)
        this.$notification.error({
          message: '错误',
          description: '请求信息错误，请稍后重试'
        })
      } finally {
        this.loading = false
      }
    },
    async detail (record) {
      try {
        record.loading = true
        const content = await detail(record.id)
        record.missionList = content.missionList
      } catch (error) {

      } finally {
        record.loading = false
      }
    },
    // 更新目标列表
    updateMissionList () {
      const recordId = this.expandedRowKeys[0]
      if (recordId) {
        const record = this.data.find(item => (item.id === recordId))
        if (record.id === this.expandedRowKeys[0]) {
          this.detail(record)
        }
      }
    },
    // 更新团战列表
    async updateList () {
      await this.handleSearch(true)
      this.updateMissionList()
    },

    // 删除团战
    async del (id) {
      try {
        this.loading = true
        await del(id)
        this.updateList()
      } catch (error) {

      } finally {
        this.loading = false
      }
    },
    // 显示编辑模块
    showEditInstanceModal (record) {
      this.$refs.editInstanceModal.show(record)
    },
    // 显示增加任务模块
    showAddMissionModal (record) {
      this.$refs.addMissionModal.show(record, this.type)
    },
    // 任务列表展开
    expand (expanded, record) {
      if (expanded) {
        this.expandedRowKeys.splice(0, 1, record.id)
        this.detail(record)
      } else {
        this.expandedRowKeys.splice(0, 1)
      }
    },
    // 删除目标
    async removeMission (record, missionId) {
      try {
        record.loading = true
        await removeMission({
          instanceId: record.id,
          missionId
        })
        this.detail(record)
      } catch (error) {

      } finally {
        record.loading = false
      }
    }
  }
}
</script>
<style lang="less">
.instance-list{
  &__table {
    margin-top: 10px;
  }
}
</style>
